//
//  CMDBRegisterViewController.swift
//  CMDB
//
//  Created by 王磊 on 05/05/2017.
//  Copyright © 2017 CMDB. All rights reserved.
//

import UIKit

private var CMDB_Register_Margin: CGFloat = (CMDB_Screen_Width - 630 * CMDB_Rate) * 0.5

class CMDBRegisterViewController: NormalTitleViewController {
    
    private var scrollView: UIScrollView = UIScrollView()
    
    private var registerTopView: CMDBRegisterTopView = CMDBRegisterTopView()
    
    private var registerBottomView: CMDBRegisterBottomView = CMDBRegisterBottomView()
    
    private var registerBtn: UIButton = UIButton(type: .Custom)
    
    private var mutableTitles: NSMutableArray = NSMutableArray(array: ["曾用名 1","曾用名 2","曾用名 3"])
    
    private var regTempParam: CMDBRegisterParam = CMDBRegisterParam()
    
    private var userName1: CMDBRegisterUseNameTF = CMDBRegisterUseNameTF()
    
    private var userName2: CMDBRegisterUseNameTF = CMDBRegisterUseNameTF()
    
    private var userName3: CMDBRegisterUseNameTF = CMDBRegisterUseNameTF()
    
    private var tempCount: Int = 1
    
    override func setup() {
        super.setup()
        
        buildRegisterScrollView()
        
        buildRegisterTopView()
        
        buildRegisterBottomView()
        
        buildRegisterBtnView()
        
        buildRegisterUseNamesView()
    }
    deinit {
        
        registerTopView.verify.destroyTimer()
        
        printLog("CMDBRegisterViewController_deinit")
        
    }
}

extension CMDBRegisterViewController {
    
    private func buildRegisterScrollView() {
        
        scrollView.showsVerticalScrollIndicator = false
        
        scrollView.showsHorizontalScrollIndicator = false
        
        contentView?.addSubview(scrollView)
        
        scrollView.frame = view.bounds
        
        scrollView.bounces = true
    }
    
    private func buildRegisterTopView() {
        
        scrollView.addSubview(registerTopView)
        
        registerTopView.frame = CGRectMake(CMDB_Register_Margin, 0, width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 4)
        
        registerTopView.addTarget(self, action: #selector(keyboardReturn), controlEvent: .ReturnKey)
        
    }
    private func buildRegisterUseNamesView() {
        
        scrollView.addSubview(userName1)
        
        userName1.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 4, width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
        
        let starAttr = [NSFontAttributeName: CMDB_Register_TF_FONT,NSForegroundColorAttributeName: UIColor.clearColor(),NSKernAttributeName: 1]
        
        let starText = "*"
        
        let textAttr = [NSFontAttributeName: CMDB_Register_TF_FONT,NSForegroundColorAttributeName: word87Color]
        
        var mutable = NSMutableAttributedString(string: starText, attributes: starAttr)
        
        mutable.appendAttributedString(NSAttributedString(string: "曾用名 1:", attributes: textAttr))
        
        userName1.attrText = mutable
        
        userName1.addBtn.addTarget(self, action: #selector(userName1AddBtnClick), forControlEvents: .TouchUpInside)
        
        let placeHolderAttr = [NSFontAttributeName: CMDB_Register_TF_FONT,NSForegroundColorAttributeName: CMDB_Register_TF_PlaceHolder_Color]
        
        userName1.placeHolderAttr = NSAttributedString(string: "请输入您的曾用名", attributes: placeHolderAttr)
        
        scrollView.addSubview(userName2)
        
        scrollView.sendSubviewToBack(userName2)
        
        userName2.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 4, width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
        
        userName2.hidden = true
        
        mutable = NSMutableAttributedString(string: starText, attributes: starAttr)
        
        mutable.appendAttributedString(NSAttributedString(string: "曾用名 2:", attributes: textAttr))
        
        userName2.attrText = mutable
        
        userName2.addBtn.addTarget(self, action: #selector(userName2AddBtnClick), forControlEvents: .TouchUpInside)
        
        userName2.placeHolderAttr = NSAttributedString(string: "请输入您的曾用名", attributes: placeHolderAttr)
        
        scrollView.addSubview(userName3)
        
        scrollView.sendSubviewToBack(userName3)
        
        userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 4, width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
        
        userName3.hidden = true
        
        mutable = NSMutableAttributedString(string: starText, attributes: starAttr)
        
        mutable.appendAttributedString(NSAttributedString(string: "曾用名 3:", attributes: textAttr))
        
        userName3.attrText = mutable
        
        userName3.addBtn.addTarget(self, action: #selector(userName3AddBtnClick), forControlEvents: .TouchUpInside)
        
        userName3.placeHolderAttr = NSAttributedString(string: "请输入您的曾用名", attributes: placeHolderAttr)
        
        userName1.returnKeyType = .Next
        
        userName2.returnKeyType = .Next
        
        userName3.returnKeyType = .Next
        
        userName1.addBtn.selected = false
        
        userName2.addBtn.selected = true
        
        userName3.addBtn.selected = true
        
        userName1.addTarget(self, action: #selector(keyboardReturn), controlEvent: ControlEvent.ReturnKey)
        
        userName2.addTarget(self, action: #selector(keyboardReturn), controlEvent: ControlEvent.ReturnKey)
        
        userName3.addTarget(self, action: #selector(keyboardReturn), controlEvent: ControlEvent.ReturnKey)
        
    }
    @objc private func userName1AddBtnClick() {
        
        if userName2.hidden {
            
            userName2.hidden = false
            
            UIView.animateWithDuration(0.3, animations: {
                [weak self] in
                
                self!.userName2.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 6, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
                
                }, completion: { [weak self] (isFinished) in
                    
                    self!.userName2.hidden = false
                    
                    self!.userName2.becomeFirstResponder()
                    
                    self!.tempCount += 1
                    
                    self!.setContentSize()
                    
                })
            
        } else if userName3.hidden {
            
            userName3.hidden = false
            
            userName1.addBtn.hidden = true
            
            UIView.animateWithDuration(0.3, animations: {
                [weak self] in
                
                self!.userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 6, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 7, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
                
                }, completion: { [weak self] (isFinished) in
                    
                    self!.userName3.becomeFirstResponder()
                    
                    self!.tempCount += 1
                    
                    self!.setContentSize()
                    
                })
        }
    }
    
    @objc private func userName2AddBtnClick() {
        
        if userName3.hidden {
            
            userName2.tf.text = nil
            
            userName2.text = ""
            
            UIView.animateWithDuration(0.3, animations: {
                [weak self] in
                
                self!.userName2.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 4, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 4, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
                
                }, completion: { [weak self] (isFinished) in
                    
                    self!.userName1.becomeFirstResponder()
                    
                    self!.userName2.hidden = true
                    
                    self!.tempCount -= 1
                    
                    self!.setContentSize()
                })
            
            
        } else {
            
            userName3.tf.text = nil
            
            userName3.text = ""
            
            userName1.addBtn.hidden = false
            
            UIView.animateWithDuration(0.3, animations: {
                [weak self] in
                
                self!.userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
                
                self!.registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 6, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
                
                }, completion: { [weak self] (isFinished) in
                    
                    self!.userName2.becomeFirstResponder()
                    
                    self!.userName3.hidden = true
                    
                    self!.tempCount -= 1
                    
                    self!.setContentSize()
                })
            
        }
    }
    @objc private func userName3AddBtnClick() {
        
        userName1.addBtn.hidden = false
        
        UIView.animateWithDuration(0.3, animations: {
            [weak self] in
            
            self!.userName3.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height)
            
            self!.registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 6, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
            
            }, completion: { [weak self] (isFinished) in
                
                self!.userName3.hidden = true
                
                self!.userName2.becomeFirstResponder()
                
                self!.tempCount -= 1
                
                self!.setContentSize()
            })
    }
    
    private func buildRegisterBottomView() {
        
        scrollView.addSubview(registerBottomView)
        
        registerBottomView.frame = CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 5, width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6 + 88 * CMDB_Rate * 3)
        
        setContentSize()
        
        registerBottomView.addTarget(self, action: #selector(keyboardReturn), controlEvent: ControlEvent.ReturnKey)
        
    }
    private func buildRegisterBtnView() {
        
        registerBottomView.addSubview(registerBtn)
        
        registerBtn.setTitle("注册", forState: .Normal)
        registerBtn.setTitle("注册", forState: .Highlighted)
        
        registerBtn.setTitleColor(UIColor.Hex6(0xffffff, alpha: 0.54), forState: .Highlighted)
        
        registerBtn.setTitleColor(UIColor.Hex6(0xffffff), forState: .Normal)
        
        registerBtn.backgroundColor = UIColor.Hex6(0xff6d00, alpha: 54)
        
        registerBtn.titleLabel!.font = CMDB_17_FONT
        
        registerBtn.addTarget(self, action: #selector(regTriggrred), forControlEvents: .TouchUpInside)
        
        registerBtn.layer.cornerRadius = 5
        
        //        CGRectMake(CMDB_Register_Margin, CMDB_Register_TF_Height * 6, self!.width - CMDB_Register_Margin * 2, CMDB_Register_TF_Height * 6)
        
        registerBtn.frame = CGRectMake(0, 6 * CMDB_Register_TF_Height + 88 * CMDB_Rate, registerBottomView.width, 88 * CMDB_Rate)
        
        
    }
    
    private func setContentSize() {
        
        let height = 11 * CMDB_Register_TF_Height + 88 * CMDB_Rate * 3 + CMDB_Register_TF_Height * CGFloat(tempCount)
        
        printLog(height)
        
        scrollView.contentSize = CGSizeMake(width , height)
    }
}
extension CMDBRegisterViewController {
    
    
    @objc private func keyboardReturn(argu: ArguInfo) {
        if argu.view == registerTopView.verify {
            
            if argu.controlEvent == .Vcode {
                
                let vcodeParam = CMDBVCodeParam()
                
                vcodeParam.phone = registerTopView.phone.text
                
                vcodeParam.vcodeType = .Reg
                
                do {
                    
                    try CMDBVCodeManager.getInstance.queryVCode(vcodeParam, handler: { (isVCodePost, vCodeType) in
                        
                        
                        
                        }, error: { (rescode) in
                            
                    }) {
                        
                        
                    }
                    
                } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.PhoneInvalid) {
                    
                    CMDBShowInfoManager.getInstance.showInfoWithStatus("无效手机号!")
                    
                } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.VCodeTypeUnSelected) {
                    
                    
                } catch {
                    
                    
                }
                
            }
            
        } else if argu.view == registerTopView.name {
            
            userName1.becomeFirstResponder()
            
        } else if argu.view == userName1 {
            
            userName1.resignFirstResponder()
            
            if userName2.hidden {
                
                registerBottomView.email.becomeFirstResponder()
                
            } else {
                
                userName2.becomeFirstResponder()
            }
            
        } else if argu.view == userName2 {
            
            userName2.resignFirstResponder()
            
            if userName3.hidden {
                
                registerBottomView.email.becomeFirstResponder()
            } else {
                
                userName3.becomeFirstResponder()
                
            }
            
        } else if argu.view == userName3 {
            
            userName3.resignFirstResponder()
            
            registerBottomView.email.becomeFirstResponder()
            
        } else if argu.view == registerBottomView.pwdVerify {
            
            let picker = CMDBDatePicker(frame: CGRect.zero)
            
            picker.id = "birth"
            
            picker.delegate = self
            
            picker.show(true)
            
        } else if argu.view == registerBottomView.sex {
            
            regTempParam.genderType = argu.controlEvent == ControlEvent.Male ? CMDBGenderType.Mail : CMDBGenderType.Femail
            
        } else if argu.view == registerBottomView.birthday {
            
            let picker = CMDBDatePicker(frame: CGRect.zero)
            
            picker.delegate = self
            
            picker.id = "birth"
            
            picker.show(true)
            
        } else if argu.view == registerBottomView.trade {
            
            let picker = CMDBPickerView(frame: CGRect.zero)
            
            let df = NSDateFormatter()
            
            df.dateFormat = "yyyy"
            
            let str = df.stringFromDate(NSDate())
            
            let numbers = (Int(str)! - 60)..<(Int(str)! + 1)
            
            let strs = numbers.map({
                
                return "\($0)年"
            })
            
            picker.updateData(strs)
            
            picker.delegate = self
            
            picker.show(true)
            
        }
        
    }
}
extension CMDBRegisterViewController: CMDBDatePickerDelegate {}

extension CMDBRegisterViewController {
    
    func confirmTriggered(datePicker: CMDBDatePicker) {
        
        let df = NSDateFormatter()
        
        df.dateFormat = "yyyy-MM-dd"
        
        regTempParam.birthday = df.stringFromDate(datePicker.currentDate!)
        
        let attr = [NSFontAttributeName: CMDB_15_FONT,NSForegroundColorAttributeName: word87Color]
        
        registerBottomView.birthday.detailLabel.attributedText = NSAttributedString(string: regTempParam.birthday, attributes: attr)
        
    }
}

extension CMDBRegisterViewController: CMDBPickerDelegate {}
extension CMDBRegisterViewController {
    
    func pickerConfirmTriggered(datePicker: CMDBPickerView) {
        
        var trade: NSString = datePicker.currentDate ?? ""
        
        let attr = [NSFontAttributeName: CMDB_15_FONT,NSForegroundColorAttributeName: word87Color]
        
        registerBottomView.trade.detailLabel.attributedText = NSAttributedString(string: trade as String, attributes: attr)
        
        trade = trade.substringToIndex(trade.length - 1)
        
        printLog(trade)
        
        regTempParam.trade = trade as String
    }
}

extension CMDBRegisterViewController {
    
    @objc private func regTriggrred() {
        
        let associate = CMDBAssociateViewController()
        
        associate.title = "关联作品"
        
        navigationController?.pushViewController(associate, animated: true)
        
        
        //        可变数组可以删除对象
        
        let regParam = CMDBRegisterParam()
        
        regParam.phone = registerTopView.phone.text
        
        regParam.vcode = registerTopView.verify.text
        
        regParam.inviteCode = registerTopView.invite.text
        
        regParam.name = registerTopView.name.text
        
        if !userName1.text.isEmpty {
            
            regParam.useTempNames += [userName1.text]
        }
        
        if !userName2.text.isEmpty {
            
            regParam.useTempNames += [userName2.text]
        }
        
        if !userName3.text.isEmpty {
            regParam.useTempNames += [userName3.text]
        }
        
        regParam.birthday = regTempParam.birthday
        
        regParam.email = registerBottomView.email.text
        
        regParam.genderType = regTempParam.genderType
        
        regParam.trade = regTempParam.trade
        
        regParam.pwd = registerBottomView.pwd.text
        
        regParam.submitPwd = registerBottomView.pwdVerify.text
        
        printLog(regParam.useNames)
        
        do {
            
            try CMDBRegisterManager.getInstance.reg(regParam, handler: { [weak self](account) in
                
                let associate = CMDBAssociateViewController()
                
                associate.title = "关联作品"
                
                self!.navigationController?.pushViewController(associate, animated: true)
                
                }, error: { (rescode) in
                    
                }, faliure: {
                    
            })
            
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.PhoneInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("无效手机号!")
            
        }catch  CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.VCodeInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("验证码不正确!")
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.PasswordInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("密码长度最少为8位数字与字母组合!")
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.NewPasswordInvalid) {
            CMDBShowInfoManager.getInstance.showInfoWithStatus("密码长度最少为8位数字与字母组合!")
            
        } catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.OldPwdNotMatchNewPwd) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("两次输入密码不匹配!")
            
        }catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.NameInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("姓名不能为空!")
            
        }catch CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.BirthdayInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("请选择生日!")
            
        }catch  CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.TradeInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("请选择入行年份!")
            
        } catch  CMDBUserControllerExceptionType.ExceptionCode(code: CMDBUserControllerExceptionCodeType.EmailInvalid) {
            
            CMDBShowInfoManager.getInstance.showInfoWithStatus("请输入正确的邮箱!")
            
        } catch {
            
            
            
        }
        
    }
}
